package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableSaveMoneyCardMemberSpecialPrice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagSaveMoneyCardMemberSpecialPrice {
    public long uid;
    public int baoguo_card_state;
    public int is_haojie_card_label;
    public int baoguo_card_vaild_time;
    public long haojie_card_update_time;
    public long baoguo_card_update_time;

    public static Logger LOG = LoggerFactory.getLogger(TagSaveMoneyCardMemberSpecialPrice.class);

    public TagSaveMoneyCardMemberSpecialPrice() {}

    public TagSaveMoneyCardMemberSpecialPrice(
            long uid,
            int baoguo_card_state,
            int is_haojie_card_label,
            int baoguo_card_vaild_time,
            long haojie_card_update_time,
            long baoguo_card_update_time) {
        this.uid = uid;
        this.baoguo_card_state = baoguo_card_state;
        this.is_haojie_card_label = is_haojie_card_label;
        this.baoguo_card_vaild_time = baoguo_card_vaild_time;
        this.haojie_card_update_time = haojie_card_update_time;
        this.baoguo_card_update_time = baoguo_card_update_time;
    }

    public static TagSaveMoneyCardMemberSpecialPrice init(long uid) {
        return new TagSaveMoneyCardMemberSpecialPrice(uid, -1, -1, 0, 0L, 0L);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableSaveMoneyCardMemberSpecialPrice.QUERYSQL);
        DataStream<Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>> inputStream =
                tableEnv.toRetractStream(tableRes, TableSaveMoneyCardMemberSpecialPrice.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<
                                        Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>
                                                    value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagSaveMonCardMemSpecPrice-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>,
                                        Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>
                                                    value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>,
                                        String>() {
                                    ValueState<TagSaveMoneyCardMemberSpecialPrice>
                                            tbSvMonCardMemSpcPrcVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tbSvMonCardMemSpcPrcVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagSaveMoneyCardMemberSpecialPrice>(
                                                                        "tagSvMonCardMemSpcPrcVState",
                                                                        TagSaveMoneyCardMemberSpecialPrice
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableSaveMoneyCardMemberSpecialPrice>
                                                    value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int type = value.f1.getType();
                                        int state = value.f1.getState();
                                        long update_time = value.f1.getUpdate_time().getTime();

                                        TagSaveMoneyCardMemberSpecialPrice tmpState =
                                                tbSvMonCardMemSpcPrcVState.value();
                                        TagSaveMoneyCardMemberSpecialPrice curStatte =
                                                tmpState == null
                                                        ? TagSaveMoneyCardMemberSpecialPrice.init(
                                                                uid)
                                                        : tmpState;

                                        switch (type) {
                                            case 12:
                                                /** haojie card label */
                                                if (update_time
                                                                > curStatte
                                                                        .getHaojie_card_update_time()
                                                        && curStatte.getIs_haojie_card_label()
                                                                != state) {
                                                    curStatte.is_haojie_card_label = state;
                                                    curStatte.haojie_card_update_time = update_time;
                                                    JSONObject jsonObject = new JSONObject();
                                                    jsonObject.put("uid", uid);
                                                    jsonObject.put("is_haojie_card_label", state);
                                                    out.collect(jsonObject.toString());
                                                    tbSvMonCardMemSpcPrcVState.update(curStatte);
                                                }
                                                break;
                                            case 19:
                                                /** baoguo card logic */
                                                if (update_time
                                                        > curStatte.getBaoguo_card_update_time()) {
                                                    String ext = value.f1.getExt();
                                                    int vaild_time =
                                                            curStatte.getBaoguo_card_vaild_time();
                                                    try {
                                                        if (ext != null && ext.length() != 0) {
                                                            JSONObject jsonObject =
                                                                    JSONObject.parseObject(ext);
                                                            if (jsonObject.containsKey(
                                                                    "validTime")) {
                                                                vaild_time =
                                                                        (int)
                                                                                (jsonObject.getLong(
                                                                                                "validTime")
                                                                                        / 1000);
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        LOG.error("Exception: " + e.getMessage());
                                                        e.printStackTrace();
                                                    }

                                                    if (vaild_time
                                                                    != curStatte
                                                                            .getBaoguo_card_vaild_time()
                                                            || state
                                                                    != curStatte
                                                                            .getBaoguo_card_state()) {
                                                        curStatte.baoguo_card_state = state;
                                                        curStatte.baoguo_card_vaild_time =
                                                                vaild_time;
                                                        curStatte.baoguo_card_update_time =
                                                                update_time;
                                                        JSONObject jsonObject = new JSONObject();
                                                        jsonObject.put("uid", uid);
                                                        jsonObject.put("baoguo_card_state", state);
                                                        if (vaild_time != 0) {
                                                            jsonObject.put(
                                                                    "baoguo_card_valid_time",
                                                                    vaild_time);
                                                        }
                                                        out.collect(jsonObject.toString());
                                                        tbSvMonCardMemSpcPrcVState.update(
                                                                curStatte);
                                                    }
                                                }

                                                break;
                                            default:
                                                LOG.warn("uid:" + uid + " type not support now!!");
                                                break;
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getBaoguo_card_state() {
        return baoguo_card_state;
    }

    public int getIs_haojie_card_label() {
        return is_haojie_card_label;
    }

    public int getBaoguo_card_vaild_time() {
        return baoguo_card_vaild_time;
    }

    public long getHaojie_card_update_time() {
        return haojie_card_update_time;
    }

    public long getBaoguo_card_update_time() {
        return baoguo_card_update_time;
    }
}
